<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

</body>
<script type="text/javascript">
    // 调用方法
    function change() {
        // 获取上传的文件
        let fileInput = document.getElementById("myfileinput");
        // files 是一个 FileList 对象(类似于NodeList对象)
        let files = fileInput.files;
        let imgobj = new Image();
        let url = window.URL || window.webkitURL;
        // 手动创建一个Image对象
        imgobj.src = url.createObjectURL(files[0]);// 这里传的是File对象
        let imgBaseStr = undefined;
        // img.onload 实现图片预加载方法
        imgobj.onload = function () {
            // 进行转码
            imgBaseStr = getBase64Image(this)
        }
    }



    // 将图片转 base64
    function getBase64Image(img) {
        var canvas = document.createElement("canvas");
        canvas.width = img.width;
        canvas.height = img.height;
        var ctx = canvas.getContext("2d");
        ctx.drawImage(img, 0, 0, img.width, img.height);
        var ext = img.src.substring(img.src.lastIndexOf(".") + 1).toLowerCase();
        var dataURL = canvas.toDataURL("image/" + ext);
        return dataURL;
    }

    function toBase64() {
        var file = document.querySelector('input[type=file]').files[0];
        var reader = new FileReader();
        reader.onloadend = function () {
            $("#base64Img").attr("style", "display:inline-block;padding-bottom:10;");
            $("#base64Img").attr("src", reader.result);
            console.log(reader.result);
        }
        if (file) {
            reader.readAsDataURL(file);
        }
    }

    var options = {
        url: "${_b}/oa/zfwyw/xttzggSaveOrUpload",
        beforeSubmit: function (formData, jqForm, options) {
            return true
        }, //提交前处理
        success: function (responseText, statusText) {
            layer.close(lay);
            if (responseText.code == '200') {
                var msg = new top.$.zui.Messager('提示消息：保存成功！', {
                    type: 'success',
                    fade: true,
                    icon: 'ok-sign',
                    time: 3000,
                    scale: true
                });
                msg.show();
                //window.parent.closerefreshsmallwindow();
            }
        }, //处理完成
        error: function (error) {
            layer.close(lay);
        },
        resetForm: true,
        data: {content: editor.html(), state: state},
        dataType: 'json',
        xhr: function () {
            var xhr = $.ajaxSettings.xhr()
            if (xhr.upload) {
                xhr.upload.addEventListener(
                    'progress',
                    function (evt) {
                        //侦查附件上传情况
                        //通过事件对象侦查
                        //该匿名函数表达式大概0.05-0.1秒执行一次
                        // console.log(evt.loaded);  //已经上传大小情况
                        //evt.total; 附件总大小
                        var loaded = evt.loaded
                        var tot = evt.total
                        var per = Math.floor((100 * loaded) / tot) //已经上传的百分比
                        var son = document.getElementById('progressBar')
                        if (son != null) {
                            son.innerHTML = per + '%'
                            son.style.width = per + '%'
                        }
                    },
                    false
                )
                return xhr
            }
        },
    }
    $("#form").ajaxSubmit(options)
</script>

<script language="javascript">
    $(function() {
        $("#file_upload").change(function() {
            var $file = $(this);
            var fileObj = $file[0];
            var windowURL = window.URL || window.webkitURL;
            var dataURL;
            var $img = $("#preview");

            if(fileObj && fileObj.files && fileObj.files[0]){
                dataURL = windowURL.createObjectURL(fileObj.files[0]);
                $img.attr('src',dataURL);
            }else{
                dataURL = $file.val();

                // $img.css("filter",'progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod = scale,src="' + dataURL + '")');

                // var imgObj = document.getElementById("preview");
                // imgObj.style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod=scale,src=\"" + dataURL + "\")";
                // imgObj.style.width = "48px";
                // imgObj.style.height = "48px";

                var imgObj = document.getElementById("preview");
                // 两个坑:
                // 1、在设置filter属性时，元素必须已经存在在DOM树中，动态创建的Node，也需要在设置属性前加入到DOM中，先设置属性在加入，无效；
                // 2、src属性需要像下面的方式添加，上面的两种方式添加，无效；
                imgObj.style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod=scale)";
                imgObj.filters.item("DXImageTransform.Microsoft.AlphaImageLoader").src = dataURL;

            }
        });
    });
</script>

<script>
    $("#fileimg").on("change", function () {
        var file = document.getElementById('fileimg').files[0];
        var aa = $("#fileimg").val().toLowerCase().split('.');
        if (typeof FileReader == "undefined") {
            if (aa[aa.length - 1] == 'gif' || aa[aa.length - 1] == 'jpg' || aa[aa.length - 1] == 'bmp' ||
                aa[aa.length - 1] == 'png' || aa[aa.length - 1] == 'jpeg') {
                // var imagSize = document.getElementById("fileimg").files[0].size;
                // if (imagSize < 1024 * 1024 * 3) {
                //
                // }
            } else {
                //二者区别自行百度
                layer.msg("请选择格式为*.jpg、*.gif、*.bmp、*.png、*.jpeg 的图片", {icon: 2, time: 1500});
                return false;
            }
            var lay = layer.load({shade: [0.1]});
            var options = {
                url: config.base_server + "api-user/userfile/getImgBase64",
                beforeSubmit: function (formData, jqForm, options) {
                    return true
                }, //提交前处理
                beforeSend: function (xhr) {
                    debugger
                    var token = config.getToken();
                    if (token) {
                        xhr.setRequestHeader('Authorization', 'bearer ' + token.access_token);
                    }
                },
                success: function (responseText, statusText) {
                    layer.close(lay);
                    $("#progressBar").html("");
                    // debugger
                    if (responseText.resp_code == '0') {
                        var img = $("#base64Img").find("img")
                        $("#base64Img").attr("style", "display:block;padding-bottom: 10px;position: relative;");
                        img.attr("src", responseText.resp_msg);
                        $("#menuimg").val(responseText.resp_msg);
                    } else {
                        layer.msg("上传失败", {icon: 2, time: 1500});
                    }
                }, //处理完成
                error: function (error) {
                    layer.close(lay);
                    $("#progressBar").html("");
                    layer.msg("上传失败", {icon: 2, time: 1500});
                },
                resetForm: true,
                data: {},
                dataType: 'json',
                xhr: function () {
                    var xhr = $.ajaxSettings.xhr()
                    if (xhr.upload) {
                        xhr.upload.addEventListener(
                            'progress',
                            function (evt) {
                                //侦查附件上传情况
                                //通过事件对象侦查
                                //该匿名函数表达式大概0.05-0.1秒执行一次
                                // console.log(evt.loaded);  //已经上传大小情况
                                //evt.total; 附件总大小
                                var loaded = evt.loaded
                                var tot = evt.total
                                var per = Math.floor((100 * loaded) / tot) //已经上传的百分比
                                var son = document.getElementById('progressBar')
                                if (son != null) {
                                    son.innerHTML = per + '%'
                                    son.style.width = per + '%'
                                }
                            },
                            false
                        )
                        return xhr
                    }
                },
            }
            $("#fromimg").ajaxSubmit(options)
        } else {
            var reader = new FileReader();
            reader.onloadend = function () {
                var img = $("#base64Img").find("img")
                $("#base64Img").attr("style", "display:block;padding-bottom: 10px;");
                img.attr("src", reader.result);
                $("#menuimg").val(reader.result)
            }
            if (file) {
                reader.readAsDataURL(file);
            }
        }
    })
</script>
</html>